<template>
  <div class="pagination">
    <button @click="$emit('getPageNo',pageNo-1)" :disabled="pageNo===1">上一页</button>

    <button v-show="startNumAndEndNum.startNum>1" @click="$emit('getPageNo',1)" :class="{pageBtnColor:pageNo===1}">1
    </button>
    <button v-show=" startNumAndEndNum.startNum>2">···
    </button>

    <!--v-for可以遍历数组、数字、对象、迭代器、字符串-->
    <button v-for="(page,index) in startNumAndEndNum.endNum" :key="index" v-show="page>=startNumAndEndNum.startNum"
            :class="{pageBtnColor:pageNo===page}"
            @click="$emit('getPageNo',page)"
    >
      {{ page }}
    </button>

    <button v-show="startNumAndEndNum.endNum<totalPage-1">···</button>
    <button v-show="startNumAndEndNum.endNum<totalPage" @click="$emit('getPageNo',totalPage)"
            :class="{pageBtnColor:pageNo===totalPage}">
      {{ totalPage }}
    </button>
    <button @click=" $emit(
    'getPageNo',pageNo+1)" :disabled="pageNo===totalPage">下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Pagination",
  props: ['pageSize', 'pageNo', 'total', 'continues'],
  computed: {
    // 计算总页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    // 连续页的开始页和结束页
    startNumAndEndNum() {
      // 解构，取需要的部分
      const {continues, totalPage, pageNo} = this
      let startNum = 0, endNum = 0;
      // 连续显示页数大于总页数的情况下
      if (continues > totalPage) {
        startNum = 0;
        endNum = totalPage
      } else {
        startNum = pageNo - parseInt(continues / 2);
        endNum = pageNo + parseInt(continues / 2);
        // 纠正不正常的现象，开始页不能小于1，结束页数不能大于总页数
        if (startNum < 1) {
          startNum = 1;
          endNum = continues
        }
        if (endNum > totalPage) {
          startNum = totalPage - continues + 1;
          endNum = totalPage
        }
      }
      // 返回一个对象
      return {startNum, endNum}
    }
  },
}
</script>

<style lang="less" scoped>
.pagination {
  // 为当前页面分页按钮设置背景颜色
  .pageBtnColor {
    background-color: pink;
  }

  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>